package com.fingard.dsp.bank.directbank.cncbi01;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CNCBI01Transaction extends CNCBI01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            CNCBI01Header tmpBankHeader = new CNCBI01Header();
            tmpBankHeader.action = "DLTRNALL";

            int tmpMaxCount7516 = 9999;
            if (this.getBankConfig().getValueAsInt("maxCount7516") > 0) {
                tmpMaxCount7516 = this.getBankConfig().getValueAsInt("maxCount7516");
            }
            BigDecimal tmpLowAmountMin = new BigDecimal("0");
            BigDecimal tmpUpAmountMax = new BigDecimal("9999999999999");
            //int tmpGlobalCount = 0;
            int intPageNumber = 20;

            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                int tmpNowStartRecord = 1;
                BigDecimal tmpNowLow = tmpLowAmountMin;
                BigDecimal tmpNowUp = tmpUpAmountMax;
                int tmpNowReadedCount = 0;
                BigDecimal tmpNowIncrement = new BigDecimal("20000");

                HashMap<String, Integer> tmpDictTotalCount = new HashMap<String, Integer>();

                boolean tmpQryNext = true;
                while (tmpQryNext && tmpRespCode.length() == 0) {//分页查询
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, tmpBankHeader);
                    xmlWriter.writeElementString("accountNo", p_req7516.actNum);
                    xmlWriter.writeElementString("lowAmount", Format.DecimalAmtFormat.format(tmpNowLow));
                    xmlWriter.writeElementString("upAmount", Format.DecimalAmtFormat.format(tmpNowUp));
                    xmlWriter.writeElementString("startDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                    xmlWriter.writeElementString("pageNumber", String.valueOf(intPageNumber));
                    xmlWriter.writeElementString("startRecord", String.valueOf(tmpNowStartRecord));
                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    XmlTextReader tmpBkReader;
                    String tmpKeyTtlCount = Format.DecimalAmtFormat.format(tmpNowLow) + "_" + Format.DecimalAmtFormat.format(tmpNowUp);
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpStatus = tmpBkReader.getFirstText("/stream/status");
                            String tmpStatusText = tmpBkReader.getFirstText("/stream/statusText");
                            if (isActiveRetCode(tmpStatus)) {
                                int tmpTotalRocords = 0;
                                if (tmpBkReader.getFirstText("/stream/totalRecords") != null && tmpBkReader.getFirstText("/stream/totalRecords").trim().length() > 0) {
                                    tmpTotalRocords = Integer.parseInt(tmpBkReader.getFirstText("/stream/totalRecords"));
                                }
                                int tmpReturnRocords = 0;
                                if (tmpBkReader.getFirstText("/stream/returnRecords") != null && tmpBkReader.getFirstText("/stream/returnRecords").trim().length() > 0) {
                                    tmpReturnRocords = Integer.parseInt(tmpBkReader.getFirstText("/stream/returnRecords"));
                                }
                                if (tmpDictTotalCount.containsKey(tmpKeyTtlCount)) {
                                    if (tmpDictTotalCount.get(tmpKeyTtlCount) != tmpTotalRocords) {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "相同条件分页查询时银行返回的总数却不同";
                                        tmpQryNext = false;
                                        break;
                                    }
                                } else {
                                    tmpDictTotalCount.put(tmpKeyTtlCount, tmpTotalRocords);
                                }
                                if (tmpTotalRocords == 0) {
                                    if (tmpNowUp == tmpUpAmountMax) {
                                        tmpQryNext = false;
                                        break;
                                    }
                                } else if (tmpTotalRocords >= tmpMaxCount7516)//达到最大限制9999
                                {
                                    if (tmpNowLow == tmpNowUp) {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "发生额为" + tmpNowLow + "的记录数达到" + tmpTotalRocords;
                                        tmpQryNext = false;
                                        break;
                                    }
                                    //达到最大限制，缩小金额范围
                                    if (tmpNowIncrement.compareTo(new BigDecimal("0.01")) == 0) {
                                        tmpNowIncrement = new BigDecimal("0");
                                    } else {
                                        tmpNowIncrement = tmpNowIncrement.divide(new BigDecimal("2"));
                                        tmpNowIncrement = new BigDecimal(Format.DecimalAmtFormat.format(tmpNowIncrement));
                                    }
                                    tmpNowUp = tmpNowLow.add(tmpNowIncrement);
                                    tmpNowStartRecord = 1;
                                    tmpNowReadedCount = 0;
                                    continue;
                                }
                                int tmpEachPiCount = 0;
                                while (tmpBkReader.read("/stream/list/row")) {
                                    tmpEachPiCount++;
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("oppOpenBankName");
                                    tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("oppAccountNo");//对方账号
                                    tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("oppAccountName");//对方户名
                                    String creditDebitFlag = tmpBkReader.readedXElement.getSingleText("creditDebitFlag");//<!--借贷标识 借：D，贷：C char(1)-->
                                    String tranAmount = tmpBkReader.readedXElement.getSingleText("tranAmount");
                                    if (creditDebitFlag != null) {
                                        if (creditDebitFlag.equals("D")) //借贷标识
                                        {
                                            if (tranAmount.indexOf("-") >= 0) {
                                                tmpRetDetail.cdFlag = "2";
                                            } else {
                                                tmpRetDetail.cdFlag = "1";
                                            }
                                        } else {
                                            if (tranAmount.indexOf("-") >= 0) {
                                                tmpRetDetail.cdFlag = "1";
                                            } else {
                                                tmpRetDetail.cdFlag = "2";
                                            }
                                        }
                                    }
                                    tmpRetDetail.tranAmt = tranAmount.replace("-", "");
                                    tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("tranNo").trim();
                                    tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance").trim();

                                    String tranDate = tmpBkReader.readedXElement.getSingleText("tranDate");
                                    String tranTime = tmpBkReader.readedXElement.getSingleText("tranTime");
                                    String valueDate = tmpBkReader.readedXElement.getSingleText("valueDate");
                                    tmpRetDetail.tranDate = tranDate.substring(0, 4) + "-" + tranDate.substring(4, 6) + "-" + tranDate.substring(6, 8);
                                    if (StringHelper.hasAnyChar(tranTime)) {
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + tranTime.substring(0, 2) + ":" + tranTime.substring(2, 4) + ":" + tranTime.substring(4, 6);
                                    } else {
                                        tmpRetDetail.tranTime = tmpRetDetail.tranDate;
                                    }
                                    if (StringHelper.hasAnyChar(valueDate)) {
                                        tmpRetDetail.valueDate = valueDate.substring(0, 4) + "-" + valueDate.substring(4, 6) + "-" + valueDate.substring(6, 8);
                                    } else {
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                    }
                                    tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("abstract");
                                    tmpRetDetail.abstr = pickupAbstr(tmpRetDetail.usage);
                                    tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("sumTranNo");
                                    tmpRetDetail.payCode = tmpBkReader.readedXElement.getSingleText("hostTranCode");

                                    if (StringHelper.isNullOrEmpty(tmpRetDetail.actNum)) {
                                        tmpRetDetail.actNum = p_req7516.actNum;
                                    }
                                    nodeAnalysic(tmpBkReader.readedXElement, tmpRetDetail, getCharset());
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                                //tmpGlobalCount += tmpEachPiCount;//全部已查数，仅统计
                                tmpNowReadedCount += tmpEachPiCount;//本次分页已查数
                                if (tmpEachPiCount != tmpReturnRocords) {
                                    tmpQryNext = false;
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "银行预期返回" + tmpReturnRocords + "条，实际读取" + tmpEachPiCount + "条";
                                    break;
                                }
                                if (tmpNowReadedCount < tmpTotalRocords)//查询下一页
                                {
                                    tmpNowStartRecord = tmpNowReadedCount + 1;//本次分页下页查询起始记录号
                                } else if (tmpNowReadedCount == tmpTotalRocords)//本次分页查询完毕
                                {
                                    if (tmpNowUp == tmpUpAmountMax)//查询完毕
                                    {
                                        tmpQryNext = false;
                                        break;
                                    } else//调整金额区间，继续查询
                                    {
                                        tmpNowLow = tmpNowUp.add(new BigDecimal("0.01"));
                                        tmpNowUp = tmpUpAmountMax;
                                        tmpNowStartRecord = 1;
                                        tmpNowReadedCount = 0;
                                        tmpNowIncrement = new BigDecimal("20000");
                                        continue;
                                    }
                                } else {
                                    tmpQryNext = false;
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "银行预期返回总数" + tmpTotalRocords + "条，实际读取" + tmpNowReadedCount + "条";
                                    break;
                                }
                            } else {
                                tmpQryNext = false;
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpStatusText;
                                break;
                            }
                        } else {
                            tmpQryNext = false;
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    } else {
                        tmpQryNext = false;
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        tmpQryNext = false;
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        tmpReq7516.higherLevelAct = p_req7515.higherLevelAct;
        tmpReq7516.actBankType = p_req7515.actBankType;
        tmpReq7516.tranNo = p_req7515.tranNo;
        return d_7516_HisTrans(tmpReq7516);
    }
}
